<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <el-form ref="formRef" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="原密码" prop="old_password">
        <el-input v-model.trim="form.old_password" />
      </el-form-item>
      <el-form-item label="新密码" prop="new_password">
        <el-input v-model.trim="form.new_password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { setPwd } from '@/api/table'
  import { isPassword } from '@/utils/validate'
  export default defineComponent({
    name: 'TableEdit',
    setup() {
      const $baseMessage = inject('$baseMessage')
      const validatePassword = (rule, value, callback) => {
        if (!isPassword(value)) callback(new Error('密码不能少于6位'))
        else callback()
      }
      const state = reactive({
        formRef: null,
        form: {
          old_password: '',
          new_password: '',
        },
        rules: {
          old_password: [
            {
              required: true,
              trigger: 'blur',
              validator: validatePassword,
            },
          ],
          new_password: [
            {
              required: true,
              trigger: 'blur',
              validator: validatePassword,
            },
          ],
        },
        title: '',
        dialogFormVisible: false,
      })
      const showEdit = () => {
        state.title = '修改密码'
        state.dialogFormVisible = true
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {
          old_password: '',
          new_password: '',
        }
        state.dialogFormVisible = false
      }
      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            const { message } = await setPwd(state.form)
            $baseMessage(message, 'success', 'vab-hey-message-success')
            close()
          }
        })
      }

      return {
        ...toRefs(state),
        showEdit,
        close,
        save,
      }
    },
  })
</script>
